import mimetypes

from FileUtils import *
from urllib.parse import quote
import json
import requests
import os
import re as match



# Time: 2020/08/09 22:01 Finish
# Author: Jamie793/Jamiexu
# Site: https://blog.jamiexu.cn
# Email: doxm@foxmail.com
# The coding api from BaiDuWenKuApi,Jamie793/Jamiexu analysis and writed



# 调用checkSensitiveWord接口检查敏感字符
#
# 调用previewfile接口检查文件是否上传过了
#
# 调用uploadpartfile接口上传文件块
#
# 调用completefile接口完成上传，返回doc_id: d4337067a100a6c30c22590102020740be1ecd86
#
# 调用addpublicdoc接口进行提交文档


class WenKuApi:
    def __init__(self, cookie):
        self.cookie = cookie
        self.token = self.getToken()

    # 获取Token
    def getToken(self):
        body = requests.get('https://wenku.baidu.com/new', headers={
            'Cookie': self.cookie
        }).text
        return match.compile(r'\\"token\\":\\"(.*?)\\",\\"isForbiddenUploadUser\\').findall(body)[0]

    # 判断文件是否上传
    def previewFile(self, path):
        filename = quote(os.path.basename(path), 'utf-8')
        identifier = FileUtils.getFileMd5(path)
        totalSize = os.path.getsize(path)
        suffix = os.path.splitext(path)[1][1:]
        line = '---------------------------9799162065182377401316330204'
        headers = {
            'Host': 'wenku.baidu.com',
            'Content-Type': 'multipart/form-data; boundary=' + line,
            'Cookie': self.cookie
        }
        data = ''
        line = '--' + line
        data += line + '\r\n' + 'Content-Disposition: form-data; name="filename"' + '\r\n\r\n' + filename + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="identifier"' + '\r\n\r\n' + identifier + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="totalSize"' + '\r\n\r\n' + str(
            totalSize) + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="file_ext"' + '\r\n\r\n' + suffix + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="token"' + '\r\n\r\n' + self.token + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="uploadType"' + '\r\n\r\n' + '2' + '\r\n'
        data += line + '--'

        headers['Content-Length'] = str(len(data))
        response = requests.post('https://wenku.baidu.com/doc/upload/previewfile', data=data, headers=headers, ).text
        jsonData = json.loads(response)['data']
        if 'repeat_info' not in jsonData:
            return None

        if jsonData['repeat_info']['status'] == 3:
            if 'repeat_upload_docid' in jsonData:
                return jsonData['repeat_upload_docid']
            else:
                self.veriflyFile(path)
                return self.completeFile(path)
        else:
            return None

    # 文件上传完成
    def completeFile(self, path):
        filename = quote(os.path.basename(path), 'utf-8')
        identifier = FileUtils.getFileMd5(path)
        totalSize = os.path.getsize(path)
        suffix = os.path.splitext(path)[1][1:]
        line = '---------------------------9799162065182377401316330204'
        headers = {
            'Host': 'wenku.baidu.com',
            'Content-Type': 'multipart/form-data; boundary=' + line,
            'Cookie': self.cookie
        }
        data = ''
        line = '--' + line
        data += line + '\r\n' + 'Content-Disposition: form-data; name="filename"' + '\r\n\r\n' + filename + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="identifier"' + '\r\n\r\n' + identifier + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="totalSize"' + '\r\n\r\n' + str(
            totalSize) + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="file_ext"' + '\r\n\r\n' + suffix + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="token"' + '\r\n\r\n' + self.token + '\r\n'
        data += line + '--'

        headers['Content-Length'] = str(len(data))
        response = requests.post('https://wenku.baidu.com/doc/upload/completefile', data=data,
                                 headers=headers, ).text
        jsonData = json.loads(response)['data']
        if 'doc_id' in jsonData:
            return jsonData['doc_id']
        else:
            return None
            # return jsonData['doc_id']

    # 上传文件
    def uploadFile(self, path):
        chunkNumber = '1'
        chunkSize = '5242880'
        totalSize = str(os.path.getsize(path))
        currentChunkSize = totalSize
        identifier = FileUtils.getFileMd5(path)
        filename = quote(os.path.basename(path), 'utf-8')
        relativePath = filename
        totalChunks = '1'

        with open(path, 'rb') as f:
            fileData = f.read()
            f.close()

        line = '---------------------------321854291223912178431074568439'
        headers = {
            'Host': 'wenku.baidu.com',
            'Content-Type': 'multipart/form-data; boundary=' + line,
            'Cookie': self.cookie
        }
        data = ''
        line = '--' + line
        data += line + '\r\n' + 'Content-Disposition: form-data; name="chunkNumber"' + '\r\n\r\n' + chunkNumber + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="chunkSize"' + '\r\n\r\n' + chunkSize + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="currentChunkSize"' + '\r\n\r\n' + currentChunkSize + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="totalSize"' + '\r\n\r\n' + totalSize + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="identifier"' + '\r\n\r\n' + identifier + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="filename"' + '\r\n\r\n' + filename + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="relativePath"' + '\r\n\r\n' + relativePath + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="totalChunks"' + '\r\n\r\n' + totalChunks + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="object_file"; filename="' + filename + '"' + '\r\n\r\n'
        data += line + '\r\n' + 'Content-Type: ' + mimetypes.guess_type(path)[0] + '\r\n\r\n'
        fileBytes = bytes(data, encoding='utf-8') + fileData
        data2 = '\r\n'
        data2 += line + '--'
        fileBytes += bytes(data2, encoding='utf-8')
        #
        # print(str(fileBytes, 'utf-8'))
        # print(len(fileBytes))

        headers['Content-Length'] = str(len(fileBytes))
        response = requests.post('https://wenku.baidu.com/doc/upload/uploadpartfile', data=fileBytes,
                                 headers=headers).text
        jsonData = json.loads(response)['data']
        # print(jsonData)

    # 验证文件
    def veriflyFile(self, path):
        totalSize = str(os.path.getsize(path))
        identifier = FileUtils.getFileMd5(path)
        filename = quote(os.path.basename(path), 'utf-8')
        suffix = os.path.splitext(path)[1][1:]

        with open(path, 'rb') as f:
            fileData = f.read()
            f.close()

        line = '---------------------------321854291223912178431074568439'
        headers = {
            'Host': 'wenku.baidu.com',
            'Content-Type': 'multipart/form-data; boundary=' + line,
            'Cookie': self.cookie
        }
        data = ''
        line = '--' + line
        data += line + '\r\n' + 'Content-Disposition: form-data; name="filename"' + '\r\n\r\n' + filename + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="totalSize"' + '\r\n\r\n' + totalSize + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="file_ext"' + '\r\n\r\n' + suffix + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="identifier"' + '\r\n\r\n' + identifier + '\r\n'
        data += line + '\r\n' + 'Content-Disposition: form-data; name="object_file"; filename="blob"' + '\r\n\r\n'
        data += line + '\r\n' + 'Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document' + '\r\n\r\n'
        fileBytes = bytes(data, encoding='utf-8') + fileData
        data2 = '\r\n'
        data2 += line + '--'
        fileBytes += bytes(data2, encoding='utf-8')

        headers['Content-Length'] = str(len(fileBytes))
        response = requests.post('https://wenku.baidu.com/doc/upload/verifypartfile', data=fileBytes,
                                 headers=headers).text
        jsonData = json.loads(response)['data']
        print(jsonData)

    # 提交
    def addPublicFile(self, data):
        headers = {
            'Host': 'wenku.baidu.com',
            'Content-Type': 'application/json',
            'Cookie': self.cookie,
            'Content - Length': str(len(data))
        }
        response = requests.post('https://wenku.baidu.com/ndupload/proxy/doc/upload/addpublicdoc',
                                 data=bytes(data, encoding='utf-8'),
                                 headers=headers).text

    def getDisplayName(self):
        body = requests.get('https://wenku.baidu.com/user/interface/getuserinfo', headers={
            'Host': 'wenku.baidu.com',
            'Cookie': self.cookie
        }).text

        jsonData = json.loads(body)['data']
        if 'displayname' not in jsonData:
            return None

        return jsonData['displayname']
